/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import entities.Server;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.PatternLayout;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 *
 * @author Leonardo Lino
 */
public class GestorZooKeeperBase {

    protected ZooKeeper zk;
    protected String thisAddress;
    protected int thisPort;
    protected String znodeName;

    protected String errorMsg;

    public GestorZooKeeperBase() {
        
        initialZKConnect();
    }

    private void initialZKConnect() {
        try {
            ConsoleAppender console = new ConsoleAppender(); //create appender
            //configure the appender
            String PATTERN = "%d [%p|%c|%C{1}] %m%n";
            console.setLayout(new PatternLayout(PATTERN));
            console.setThreshold(org.apache.log4j.Level.ERROR);
            console.activateOptions();
            org.apache.log4j.BasicConfigurator.configure(console);

            connect(ConfigGeral.CG_ZOOKEEP_IP + ":" + ConfigGeral.CG_ZOOKEEP_PORT, 455);
        } catch (IOException ex) {
            System.err.println(ex.toString());
        } catch (InterruptedException ex) {
            System.err.println(ex.toString());
        }

    }

    public ZooKeeper connect(String hosts, int timeout)
            throws IOException, InterruptedException {

        final CountDownLatch signal = new CountDownLatch(1);

        zk = new ZooKeeper(hosts, timeout, null);
        return zk;
    }

    public void create(String groupName, byte[] dataArray)
            throws KeeperException, InterruptedException {

        String path = "/" + groupName;
        String createdPath = zk.create(path,
                dataArray,
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
    }

    public Server getPrimary() {
        Server server = null;

        try {
            Stat stat = zk.exists("/Ready/DBready", null);
            byte[] dados = zk.getData("/Ready/DBready", null, stat);

            String dadosStr = new String(dados);
            String[] piece = dadosStr.split(",");
            String[] segundo = piece[0].split(":");
            server = new Server(segundo[0], Integer.parseInt(segundo[1]));
            server.setRmiBindName(segundo[2]);

        } catch (KeeperException ex) {
            errorMsg = ex.toString();
            System.err.println("erro: " + ex.toString());
            return null;
        } catch (InterruptedException ex) {
            System.err.println("erro: " + ex.toString());
            errorMsg = ex.toString();
            return null;
        }
        return server;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public String getZnodeName() {
        return znodeName;
    }

}
